# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=libssh
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.10.4
pkgrel=2
pkgdesc="Library for accessing ssh client services through C libraries (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://www.libssh.org/"
license=('spdx:LGPL-2.1-or-later')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkg-config")
depends=("${MINGW_PACKAGE_PREFIX}-openssl"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread-git")
checkdepends=("${MINGW_PACKAGE_PREFIX}-cmocka")
validpgpkeys=('8DFF53E18F2ABC8D8F3C92237EE0FC4DCC014E3D') # Andreas Schneider <asn@cryptomilk.org>
source=("https://www.libssh.org/files/${pkgver%.*}/${_realname}-${pkgver}.tar.xz"{,.asc}
        "mingw-as-unix.patch"
         001-install-static-lib.patch
         010-lld.patch)
sha256sums=('07392c54ab61476288d1c1f0a7c557b50211797ad00c34c3af2bbc4dbc4bd97d'
            'SKIP'
            '9bd22f20d4d9ae7bde7d4838467f41ec1af92017d21e8d318648748d67ea6d81'
            'ff70c3719ad033fac8ed0b6c9c15c66160bda1dedfbcbfb78227e015ccab72c1'
            'b466e14c1f3e34b0891ea04ad8c008984cada054398cadd2fb2bb44460ae198f')

prepare() {
  cd ${srcdir}/${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/mingw-as-unix.patch
  patch -p1 -i ${srcdir}/001-install-static-lib.patch
  patch -p1 -i ${srcdir}/010-lld.patch
}

build() {
  [[ -d ${srcdir}/build-${MSYSTEM} ]] && rm -rf ${srcdir}/build-${MSYSTEM}
  mkdir -p ${srcdir}/build-${MSYSTEM} && cd ${srcdir}/build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DWITH_GSSAPI=OFF \
    -DUNIT_TESTING=OFF \
    -DBUILD_STATIC_LIB=ON \
    -DBUILD_SHARED_LIBS=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/cmake -DUNIT_TESTING=ON ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake --build .
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/libssh/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
